<template>


  <van-tabs v-model:active="active">

    <van-tab title="推荐"></van-tab>
    <van-tab title="装修">内容 2</van-tab>
    <van-tab title="找室友">内容 3</van-tab>

    <van-icon name="sign"  @click="goToSign"/>
  </van-tabs>

  <van-list :finished="finished" @load="onLoad">
    <van-cell v-for="postPage in postPages" :key="postPage.id" @click="goToPost(postPage.id)">
      <div class="post-item">
        <img :src="postPage.coverImage" alt="cover" class="cover-image"/>

        <div class="post-info">
          <img :src="postPage.avatar" alt="avatar" class="avatar"/>
          <span class="nickname">{{ postPage.nickname }}</span>
          <span class="title">{{ postPage.title }}</span>
        </div>
        <div class="like-count">
          <van-icon name="like-o" > {{ postPage.likeCount }}</van-icon></div>
      </div>

    </van-cell>
  </van-list>
</template>

<script setup>
import { ref } from 'vue';

import { Toast } from 'vant';
import {get} from "../../util/request.js";
import {useRouter} from "vue-router"; // 假设你使用了 Vant 的 Toast 组件


const active = ref(0); // 初始激活的 tab 索引为 0，即“推荐”
const router = useRouter();
const postPages = ref([]);
const finished = ref(false);

import { onMounted } from 'vue';

// onMounted(() => {
//   onLoad();
// });
const onLoad = () => {
  console.log('Starting to load post pages...');
  getAllPostPages()
      .then(data => {
        console.log("data内容：",data);
        postPages.value = data;
        finished.value = true;
      })
      .catch(error => {
        Toast.error('加载失败，请稍后重试');
        console.error('Failed to load post pages:', error);
      });
};

const getAllPostPages = () => {
  return new Promise((resolve, reject) => {
    get('life/postPage/all')
        .then(response => {
          console.log('API Response响应:', response);
          if (Array.isArray(response) && response.length > 0) {
            resolve(response);
          } else {
            console.error('Unexpected API Response Structure:', response);
            reject(new Error('Unexpected API Response Structure'));
          }
        })
        .catch(error => {
          console.error('API Request Failed原因:', error);
          reject(error);
        });
  });
};

const goToPost = (postPageId) => {
  router.push(`/post/${postPageId}`);
};

const goToSign = () => {
  router.push('/sign');

}

</script>

<style scoped>
.post-item {
  display: flex;
  flex-direction: column;
  margin-bottom: 16px;
}
.cover-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}
.post-info {
  display: flex;
  align-items: center;
  margin-top: 8px;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.nickname {
  margin-left: 8px;
}
.title {
  margin-left: auto;
  font-weight: bold;
}
.like-count {
  margin-top: 8px;
  color: #888;
}
</style>
